﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Publishing;

namespace Digiwijs.MasterPageStapler
{
    /// <summary>
    /// A Standard Feature Receiver
    /// </summary>
    public class Receiver : SPFeatureReceiver
    {
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            /// <summary>
            /// The Current Version of this Feature retrieves the PARENTWEB masterpage
            /// The current.Site.RootWeb can be used to inheret the RootWeb's Masterpage
            /// The current.ParentWeb can be used to inheret the ParentWeb's MasterPage
            /// </summary>
            try
            {                
                SPWeb current = (SPWeb)properties.Feature.Parent; 
                SPWeb rootWeb = current.ParentWeb;

                current.Properties["MasterUrl"] = current.MasterUrl;
                current.Properties["CustomMasterUrl"] = current.CustomMasterUrl;
                current.Properties["AlternateCcssUrl"] = current.AlternateCssUrl;
                current.Properties["SiteLogoUrl"] = current.SiteLogoUrl;
                current.Properties["Theme"] = current.Theme;

                current.MasterUrl = rootWeb.MasterUrl;
                current.CustomMasterUrl = rootWeb.CustomMasterUrl;
                current.AlternateCssUrl = rootWeb.AlternateCssUrl;
                current.SiteLogoUrl = rootWeb.SiteLogoUrl;
                current.ApplyTheme(rootWeb.Theme);
                
                current.Update();
            }
            catch { }
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            /// <summary>
            /// Resets everything to default properties
            /// </summary>
            try
            {
                SPWeb current = (SPWeb)properties.Feature.Parent;
                SPWeb rootWeb = current.ParentWeb;

                current.MasterUrl = current.Properties["MasterUrl"];
                current.CustomMasterUrl = current.Properties["CustomMasterUrl"];
                current.AlternateCssUrl = current.Properties["AlternateCcssUrl"];
                current.SiteLogoUrl = current.Properties["SiteLogoUrl"];
                current.ApplyTheme(current.Properties["Theme"]);

                current.Update();
            }
            catch { }
        
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        { }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        { }
    }
}
